package com.zhaolang.qogir.domain.impl;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.zhaolang.qogir.bean.OrderBean;
import com.zhaolang.qogir.bean.OrderMenu;
import com.zhaolang.qogir.bean.ProductBean;
import com.zhaolang.qogir.bean.ProductClassBean;
import com.zhaolang.qogir.cache.SharePreCacheHelper;
import com.zhaolang.qogir.domain.BaseCall;
import com.zhaolang.qogir.domain.BaseResp;
import com.zhaolang.qogir.domain.OrderManage;
import com.zhaolang.qogir.domain.WaresManage;
import com.zhaolang.qogir.server.ClientCallbackImpl;
import com.zhaolang.qogir.server.RadarProxy;
import com.zhaolang.qogir.server.ServerRequestParams;
import com.zhaolang.qogir.util.HttpConstant;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrderManageImpl extends OrderManage {
    private Context context;
    private Handler handler1;
    private ServerRequestParams params;

    public OrderManageImpl(Context context) {
        this.context = context;
    }

    @SuppressLint("HandlerLeak")
    @Override
    public void readAllOrderAsync(final BaseCall<OrderReq> call) {
        handler1 = new Handler() {
            public void handleMessage(Message msg) {
                if (call != null && !call.cancel) {
                    call.call((OrderReq) msg.obj);
                }
            }
        };
        RadarProxy.getInstance(context).startServerData(getAllOrder(),
                new ClientCallbackImpl() {
                    @Override
                    public void onSuccess(String result) {
                        JSONObject jsonObject;
                        OrderReq resp = new OrderReq();
                        Log.d("Radar", "getOrderAsync: " + result);
                        try {
                            jsonObject = new JSONObject(result);
                            resp.setSuccess(jsonObject.optBoolean("success"));
                            resp.setStatusCode(jsonObject.optInt("statusCode"));
                            JSONObject jsonObject2 = new JSONObject(jsonObject.optString("message"));
                            resp.setStatus(jsonObject2.optString("status"));
                            List<OrderBean> orderList = new ArrayList<>();
                            /* parse product class bean from json object */
                            if (jsonObject2.optString("status").equals("success")) {
                                String classValues = jsonObject2.optString("orderContent");
                                Object object = new JSONTokener(classValues).nextValue();
                                if (object instanceof JSONObject) {
                                    OrderBean bean = new OrderBean();
                                    bean.setOrderId(((JSONObject) object).optString("orderId"));
                                    bean.setOrderUserId(((JSONObject) object).optString("tel"));
                                    bean.setOrderTime(((JSONObject) object).optString("order_time"));
                                    bean.setOrderCost(((JSONObject) object).optString("cost"));
                                    bean.setOrderAddressName(((JSONObject) object).optString("addr_name"));
                                    bean.setOrderUserName(((JSONObject) object).optString("user_name"));
                                    bean.setOrderStatusId(((JSONObject) object).optString("order_status"));

                                    String menu = ((JSONObject) object).optString("menu");
                                    Object menuObj = new JSONTokener(menu).nextValue();
                                    List<OrderMenu> list = new ArrayList<>();
                                    if (menuObj instanceof JSONObject) {
                                        OrderMenu orderMenu = new OrderMenu();
                                        orderMenu.setName(((JSONObject) menuObj).optString("name"));
                                        orderMenu.setPrice(((JSONObject) menuObj).optString("price"));
                                        orderMenu.setNumb(((JSONObject) menuObj).optString("numb"));
                                        list.add(orderMenu);
                                    } else if (menuObj instanceof JSONArray) {
                                        JSONArray jsonArray = (JSONArray) menuObj;
                                        for (int i = 0; i < jsonArray.length(); i++) {
                                            JSONObject obj = jsonArray.getJSONObject(i);
                                            OrderMenu orderMenu = new OrderMenu();
                                            orderMenu.setName(obj.optString("name"));
                                            orderMenu.setPrice(obj.optString("price"));
                                            orderMenu.setNumb(obj.optString("numb"));
                                            list.add(orderMenu);
                                        }
                                    }
                                    bean.setMenuList(list);
                                    orderList.add(bean);
                                    resp.setOrderBean(orderList);
                                } else if (object instanceof JSONArray) {
                                    JSONArray jsonArray = (JSONArray) object;
                                    for (int m = 0; m < jsonArray.length(); m++) {
                                        JSONObject details = jsonArray.getJSONObject(m);
                                        OrderBean bean = new OrderBean();
                                        bean.setOrderId(details.optString("orderId"));
                                        bean.setOrderUserId(details.optString("tel"));
                                        bean.setOrderTime(details.optString("order_time"));
                                        bean.setOrderCost(details.optString("cost"));
                                        bean.setOrderAddressName(details.optString("addr_name"));
                                        bean.setOrderUserName(details.optString("user_name"));
                                        bean.setOrderStatusId(details.optString("order_status"));

                                        String menu = details.optString("menu");
                                        Object menuObj = new JSONTokener(menu).nextValue();
                                        List<OrderMenu> list = new ArrayList<>();
                                        if (menuObj instanceof JSONObject) {
                                            OrderMenu orderMenu = new OrderMenu();
                                            orderMenu.setName(((JSONObject) menuObj).optString("name"));
                                            orderMenu.setPrice(((JSONObject) menuObj).optString("price"));
                                            orderMenu.setNumb(((JSONObject) menuObj).optString("numb"));
                                            list.add(orderMenu);
                                        } else if (menuObj instanceof JSONArray) {
                                            JSONArray menuArray = (JSONArray) menuObj;
                                            for (int i = 0; i < menuArray.length(); i++) {
                                                JSONObject obj = menuArray.getJSONObject(i);
                                                OrderMenu orderMenu = new OrderMenu();
                                                orderMenu.setName(obj.optString("name"));
                                                orderMenu.setPrice(obj.optString("price"));
                                                orderMenu.setNumb(obj.optString("numb"));
                                                list.add(orderMenu);
                                            }
                                        }
                                        bean.setMenuList(list);
                                        orderList.add(bean);
                                    }
                                    resp.setOrderBean(orderList);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            resp.setStatus("FAILED");
                            Log.d("Radar", "JSONException: " + e);
                        }
                        Message msg = Message.obtain();
                        msg.obj = resp;
                        handler1.sendMessage(msg);
                    }

                    @Override
                    public void onFailure(String result) {
                        BaseResp resp = new BaseResp();
                        resp.setStatus("FAILED");
                        Message msg = Message.obtain();
                        msg.obj = resp;
                        handler1.sendMessage(msg);
                        System.out.println(result);
                    }
                });
    }

    /**
     * read all order list
     *
     * @return
     */
    private ServerRequestParams getAllOrder() {
        params = getServerRequest();
        params.setRequestUrl(HttpConstant.readAllOrder(null));
        String shopId = "15651723391";
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("token", HttpConstant.TOKEN);
        param.put("SHOP_ID", shopId);
        param.put("FKEY", HttpConstant.getFKEY());
        params.setRequestParam(param);
        return params;
    }

    private ServerRequestParams getServerRequest() {
        if (params == null) {
            params = new ServerRequestParams();
        }
        return params;
    }
}
